package com.yzyz.management.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.yzyz.management.bean.AdminBean;
import com.yzyz.management.dao.AdminDao;
import com.yzyz.utils.mapper.AdminRowMapper;

public class AdminDaoImpl implements AdminDao {
	private JdbcTemplate jdbcTemplate;
	@Override
	public int add(final AdminBean admin) {
		final String sql = "insert into admin v(name, password, ownerId) values(?,?,?)";
		KeyHolder keyHolder = new GeneratedKeyHolder();
		this.jdbcTemplate.update(new PreparedStatementCreator() {
			public java.sql.PreparedStatement createPreparedStatement(
					Connection conn) throws SQLException {
				java.sql.PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
				ps.setString(1, admin.getName());
				ps.setString(2, admin.getPassword());
				ps.setInt(3, admin.getOwnerId());
				return ps;
			}
		}, keyHolder);
		return keyHolder.getKey().intValue();
	}

	@Override
	public void delete(int id) {
		String sql = "delete from admin where id=" + id;
		this.jdbcTemplate.execute(sql);

	}

	@Override
	public void update(final AdminBean admin) {
		String sql = "update admin set name=?, password=? where id=" + admin.getId();
		this.jdbcTemplate.update(sql, new PreparedStatementSetter(){

			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1, admin.getName());
				ps.setString(2, admin.getPassword());
				ps.setInt(3, admin.getId());
			}});

	}

	@Override
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AdminBean> listAll() {
		String sql = "select * from admin";
		return this.jdbcTemplate.queryForList(sql);
	}

	@SuppressWarnings("unchecked")
	@Override
	public AdminBean get(String name) {
		String sql = "select * from admin where name='" + name + "'";
		List<AdminBean> list = this.jdbcTemplate.query(sql, new AdminRowMapper());
		return list == null? null: list.get(0);
	}

}
